import fs from 'node:fs';
import path from 'node:path';
import viteCommonReactConfig from '../common.react.config';
import viteReactConfig from './react.config';

async function preview() {
  const vite = (await import('vite')).default;

  const configPath = path.join(process.cwd(), './vite.config.ts');
  let overrides = {};

  if (fs.existsSync(configPath)) {
    const configFile = await vite.loadConfigFromFile(
      { command: 'build', mode: 'production' },
      configPath,
    );
    overrides = configFile?.config || {};
  }

  const defaultConfig = vite.mergeConfig(
    await viteCommonReactConfig(),
    await viteReactConfig(),
  );
  const config = vite.mergeConfig(defaultConfig, overrides);
  const previewServer = await vite.preview(config);
  previewServer.printUrls();
  previewServer.bindCLIShortcuts({ print: true });
}
export default preview;
